from django.shortcuts import render, reverse
from django.http import HttpResponse, JsonResponse
from django.contrib.auth.hashers import make_password, check_password
from ..models import Users
import random, time, os
# from web import settings
from django.core.paginator import Paginator


# Create your views here.
# 后台会员列表
def index(request):
    # 查询所有的会员数据
    data = Users.objects.filter()

    # 接收搜索条件
    selecttype = request.GET.get('selecttype', None)
    keywords = request.GET.get('keywords', None)
    if selecttype:
        # 有搜索条件
        if selecttype == "all":
            # 按照多字段进行条件搜索
            from django.db.models import Q
            data = data.filter(
                Q(phone__contains=keywords) | Q(nickname__contains=keywords) | Q(sex__contains=keywords) | Q(
                    usertype__contains=keywords))
            # select * from users where name like '%a%' or phone like '%a%'
        else:
            serdata = {f'{selecttype}__contains': keywords}
            data = data.filter(**serdata)

    # print(data,'----------------------------')

    # 实例化分页对象 参数1,数据集,参数2,每页显示的条数
    p = Paginator(data, 3)
    # 接收当前的页码数
    inx_p = request.GET.get('page', 1)
    # 获取当前页的数据
    # userlist = p.page(inx_p)
    userlist = p.get_page(inx_p)

    # 分配数据
    content = {'data': userlist, 'contacts': userlist}
    # 加载模板
    return render(request, 'myadmin/users/index.html', content)


# 会员添加
def add(request):
    return render(request, 'myadmin/users/add.html')


# 执行会员添加
def insert(request):
    # 接收表单数据
    data = request.POST.dict()
    data.pop('csrfmiddlewaretoken')
    # print(data)

    # 密码加密
    data['password'] = make_password(data['password'], None, 'pbkdf2_sha256')

    try:
        # 检测是否上传了头像 face
        file = request.FILES.get('pic', None)
        if file:
            # 上传了头像
            data['face'] = imgupload(file)
        else:
            # 没上传就弹出,数据库中有默认值
            data.pop('pic')

        # 进行数据的添加
        obj = Users(**data)
        obj.save()
        url = reverse('myadmin_users_index')
        return HttpResponse(f'<script>alert("会员添加成功");location.href="{url}"</script>')
    except:
        url = reverse('myadmin_users_add')
        return HttpResponse(f'<script>alert("会员添加失败");location.href="{url}"</script>')


# 执行会员删除
def delete(request):
    try:
        id = request.GET.get('id')
        obj = Users.objects.get(id=id)
        # 判断当前用户是否有上传的头像(头像路径中是否包含uploads)
        try:
            if 'uploads' in obj.face:
                # 删除头像
                os.remove('.' + obj.face)
        except:
            return JsonResponse({'code': 2, 'msg': '删除头像失败'})
        # 删除用户数据
        obj.delete()
        return JsonResponse({'code': 0, 'msg': '删除成功'})
    except:
        return JsonResponse({'code': 1, 'msg': '删除失败'})


# 封装头像上传方法
def imgupload(file):
    try:
        filename = str(time.time() + random.randint(10000, 99999)) + '.' + file.name.split('.').pop()
        with open(f'./static/uploads/{filename}', 'wb+') as fp:
            fp.write(file.read())
        return f'/static/uploads/{filename}'
    except:
        return False
